package steed.tag;

import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import steed.hibernatemaster.domain.BaseDomain;
import steed.util.base.BaseUtil;
import steed.util.base.DomainUtil;
/**
 * 作用自己意会
 * @author 战马
 *
 */
public class FillInputByDomain extends TagSupport{
	private static final long serialVersionUID = -5584256537704686928L;
	private boolean readOnlyID = true;
	private String root = "$(document)";
	private String attributeKey = "domain";
	private String[] fieldsSkip;
	private String prefix = "";
	public static final String[] strNotAll = new String[]{"<",">"};

	private Object domain;
	
	public void setDomain(Object domain) {
		this.domain = domain;
	}

	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}

	public void setAttributeKey(String attributeKey) {
		this.attributeKey = attributeKey;
	}

	public void setReadOnlyID(boolean readOnlyID) {
		this.readOnlyID = readOnlyID;
	}

	public void setFieldsSkip(String fieldsSkip) {
		this.fieldsSkip = fieldsSkip.split("\\,");
	}

	public String getRoot() {
		return root;
	}
	
	public void setRoot(String root) {
		this.root = "$(document.getElementById(\""+root+"\"))";
	}

	private String dealString(String str){
		return str.replace("\"", "\\\"").replace("\n", "\\n").replace("'", "\\'");
	}
	
	@Override
	public int doStartTag() throws JspException {
		try {
			HttpServletRequest req = (HttpServletRequest) pageContext.getRequest();
			Object baseDomain;
			if (domain != null) {
				baseDomain = domain;
			}else {
				baseDomain = req.getAttribute(attributeKey);
			}
			if (baseDomain == null) {
				return SKIP_BODY;
			}
			JspWriter out = pageContext.getOut();
			out.print("<script type=\"text/javascript\">");
			out.print("function fillInputByDomain(){\n");
			out.print("var ");
			String name = baseDomain.getClass().getName().replace(".", "");
			out.print(name);
			out.print(" = ");
			out.print(root);
			out.print(";\n");
			//root = name;
			/*if (baseDomain instanceof BaseRelationalDatabaseDomain && baseDomain.getClass().getName().contains("_$$_")) {
				((BaseRelationalDatabaseDomain)baseDomain).initialize();
			}*/
			Map<String, Object> putField2Map = DomainUtil.putField2Map(baseDomain);
			for(Entry<String, Object> e:putField2Map.entrySet()){
				if (!BaseUtil.isObjEmpty(e.getValue()) && !isSkip(e.getKey())) {
					//TODO 日期智能转换 sqldate后面的.0,自动精确到日 等,
					out.print(getScript(dealString(e.getValue().toString()), prefix + e.getKey(),name));
				}
			}
			if (readOnlyID && baseDomain instanceof BaseDomain) {
				String domainIDName = DomainUtil.getDomainIDName((Class<? extends BaseDomain>) baseDomain.getClass());
				
				out.print("var steedFrameWork");
				out.print(domainIDName);
				out.print(" = $(\"[name='");
				out.print(domainIDName);
				out.print("']\",");
				out.print(name);
				out.print(");\n");
				out.print("if(steedFrameWork");
				out.print(domainIDName);
				out.print(".length > 0){\n");
				out.print("steedFrameWork");
				out.print(domainIDName);
				out.print(".attr('readOnly','readOnly')");
				out.print("\n}\n");
			}
			out.print("\n}\n");
			out.print("fillInputByDomain();");
			out.print("</script>");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return SKIP_BODY;
	}
	
	
	private boolean isSkip(String name){
		if (fieldsSkip != null) {
			for(String str:fieldsSkip){
				if (name.equals(str)) {
					return true;
				}
			}
		}
		return false;
	}
	
	private String getScript(String value,String name,String rootName){
	/*	if (!StringUtil.isStringEmpty(value)) {
			for (String temp:strNotAll) {
				if (value.contains(temp)) {
					return "";
				}
			}
		}*/
		/*name = name.replace("$", "");
		rootName = rootName.replace("$", "");*/
		String compatibilityName = (rootName+name).replace(".", "_");
		StringBuffer sb = new StringBuffer();
		sb.append("var ")
			.append(compatibilityName)
			.append(" = $(\"[name='")
			.append(name)
			.append("']\",")
			.append(rootName)
			.append(");\n")
			.append("if(")
			.append(compatibilityName)
			.append(".length > 0){\n")
			.append("var temp = ")
			.append(compatibilityName)
			.append("[0];\n")
			.append("var steed_framework_type = $(temp).attr('type');\n")
			.append("if(steed_framework_type == 'radio' || steed_framework_type == 'checkbox'){\n")
			.append(compatibilityName)
			.append(".each(function(){\nif(this.value == \"")
			.append(value)
			.append("\"){\nthis.checked=true;\nreturn false;  \n}\n});")
			.append("\n}else{\ntemp.value = '")
			.append(value)
			.append("';\n}\n}\n");
		return sb.toString();
	}
}
